import { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
import { toast } from 'sonner';
import { useLanguage } from './LanguageContext';

// 定义购物车商品类型
export interface CartItem {
  id: number;
  nameKey: string;
  price: number;
  quantity: number;
  image: string;
  selectedAttributes?: Record<string, string>;
}

// 定义购物车上下文类型
interface CartContextType {
  items: CartItem[];
  addToCart: (product: Omit<CartItem, 'quantity'>, quantity?: number) => void;
  removeFromCart: (productId: number) => void;
  updateQuantity: (productId: number, quantity: number) => void;
  clearCart: () => void;
  totalItems: number;
  totalPrice: number;
}

// 定义Action类型
type Action = 
  | { type: 'ADD_ITEM'; payload: CartItem }
  | { type: 'REMOVE_ITEM'; payload: number }
  | { type: 'UPDATE_QUANTITY'; payload: { id: number; quantity: number } }
  | { type: 'CLEAR_CART' }
  | { type: 'INITIALIZE_CART'; payload: CartItem[] };

// 初始状态
const initialState: { items: CartItem[] } = {
  items: []
};

// 购物车reducer
const cartReducer = (state: { items: CartItem[] }, action: Action): { items: CartItem[] } => {
  switch (action.type) {
    case 'ADD_ITEM': {
      const existingItemIndex = state.items.findIndex(item => item.id === action.payload.id);
      
      if (existingItemIndex >= 0) {
        // 如果商品已存在，增加数量
        const updatedItems = [...state.items];
        updatedItems[existingItemIndex].quantity += action.payload.quantity;
        return { items: updatedItems };
      } else {
        // 如果商品不存在，添加新商品
        return { items: [...state.items, action.payload] };
      }
    }
    
    case 'REMOVE_ITEM':
      return { items: state.items.filter(item => item.id !== action.payload) };
      
    case 'UPDATE_QUANTITY':
      return { 
        items: state.items.map(item => 
          item.id === action.payload.id 
            ? { ...item, quantity: action.payload.quantity } 
            : item
        ) 
      };
      
    case 'CLEAR_CART':
      return { items: [] };
      
    case 'INITIALIZE_CART':
      return { items: action.payload };
      
    default:
      return state;
  }
};

// 创建上下文
const CartContext = createContext<CartContextType | undefined>(undefined);

// 购物车提供者组件
export function CartProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(cartReducer, initialState);
  const { t } = useLanguage();
  
  // 从localStorage加载购物车数据
  useEffect(() => {
    try {
      const savedCart = localStorage.getItem('cart');
      if (savedCart) {
        const parsedCart = JSON.parse(savedCart);
        dispatch({ type: 'INITIALIZE_CART', payload: parsedCart });
      }
    } catch (error) {
      console.error('Failed to load cart from localStorage:', error);
    }
  }, []);
  
  // 将购物车数据保存到localStorage
  useEffect(() => {
    try {
      localStorage.setItem('cart', JSON.stringify(state.items));
    } catch (error) {
      console.error('Failed to save cart to localStorage:', error);
    }
  }, [state.items]);
  
  // 添加商品到购物车
  const addToCart = (product: Omit<CartItem, 'quantity'>, quantity: number = 1) => {
    dispatch({ 
      type: 'ADD_ITEM', 
      payload: { ...product, quantity } 
    });
     toast.success(`${t(product.nameKey)} ${t('addedToCart')}`, {
       className: "bg-green-600 text-white text-lg py-4 px-6 shadow-lg border-l-4 border-green-400",
       style: {
         fontSize: "1.1rem",
         fontWeight: "500",
       },
       duration: 3000,
       position: "top-center",
     });
  };
  
  // 从购物车移除商品
  const removeFromCart = (productId: number) => {
    const itemToRemove = state.items.find(item => item.id === productId);
    if (itemToRemove) {
      dispatch({ type: 'REMOVE_ITEM', payload: productId });
      toast.info(`${t(itemToRemove.nameKey)} ${t('removedFromCart')}`);
    }
  };
  
  // 更新商品数量
  const updateQuantity = (productId: number, quantity: number) => {
    if (quantity < 1) return;
    dispatch({ 
      type: 'UPDATE_QUANTITY', 
      payload: { id: productId, quantity } 
    });
  };
  
  // 清空购物车
  const clearCart = () => {
    dispatch({ type: 'CLEAR_CART' });
    toast.info(t('cartCleared'));
  };
  
  // 计算总商品数量
  const totalItems = state.items.reduce((total, item) => total + item.quantity, 0);
  
  // 计算总价格
  const totalPrice = state.items.reduce(
    (total, item) => total + item.price * item.quantity, 
    0
  );
  
  return (
    <CartContext.Provider value={{
      items: state.items,
      addToCart,
      removeFromCart,
      updateQuantity,
      clearCart,
      totalItems,
      totalPrice
    }}>
      {children}
    </CartContext.Provider>
  );
}

// 自定义hook，方便组件使用购物车上下文
export function useCart() {
  const context = useContext(CartContext);
  if (context === undefined) {
    throw new Error('useCart must be used within a CartProvider');
  }
  return context;
}